package com.bw.controller;

import com.bw.entity.User;
import com.bw.entity.Word;
import com.bw.service.FinishService;
import com.bw.service.ReportService;
import com.bw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private FinishService finishService;

    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }
    @RequestMapping("login")
    public String login(User user, HttpServletRequest request) {
        if(user == null) {
            throw new NullPointerException("user为空");
        }
        User user1 = userService.login(user.getName());
        if(user1!=null) {
            if(user1.getPassword().equals(user.getPassword())){
                request.getSession().setAttribute("user", user1);
                return "main";
            }
        }
        request.setAttribute("error", "用户名密码错误");
        return "login";
    }

    /**
     * 跳轉到查看以背单词列表
     * @return
     */
    @RequestMapping("list")
    public String list(){
        return "list";
    }

    /**
     * 以背单词列表
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("list1")
    @ResponseBody
    public List<Word> list(HttpServletRequest request,ModelAndView model) {
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user.getId());
        List<Word> wlist = userService.list(user.getId());
        /*for(Word word :wlist){
            System.out.println(word);
        }*/
        return wlist;

    }

    /**
     * 注销
     */
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:tologin";
    }

    @RequestMapping("queryStudent")
    @ResponseBody
    public List<Word> queryStudent(ModelAndView model,String date2,HttpServletRequest request){
        System.out.println(date2+"hhh");
        if(date2==null){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date2 = sdf.format(date);
        }
        Map map = new HashMap();
        User user = (User) request.getSession().getAttribute("user");
        map.put("id",user.getId());
        map.put("datea",date2);
        //查询单词集合
        List<Word> wlist = userService.wlist(map);
        return wlist;
    }
}
